package edu.mse.camel.client.uml.collab.editor;

import org.eclipse.emf.ecore.change.util.ChangeRecorder;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CommandStack;

import com.cea.papyrus.core.editor.ModelManager;

import edu.mse.camel.client.uml.collab.emflistener.CamelChangeRecorder2;

public class CamelCommandStack extends CommandStack {

	private ModelManager modelManager;

	private volatile boolean shouldRecord = true;
	
	public CamelCommandStack(ModelManager modelManager, boolean shouldRecord) {
		super();
		this.modelManager = modelManager;
		this.shouldRecord = shouldRecord;
	}
	
	private CamelChangeRecorder2 PreDo () {
		if(getShouldRecord()) {
			CamelChangeRecorder2 recorder = new CamelChangeRecorder2(modelManager.getResourceSet());
			recorder.beginRecording();
			return recorder;
		}
		else {
			return null;
		}
	}
	
	private void PostDo (CamelChangeRecorder2 recorder) {
		if(recorder != null) {
			if(recorder.IsRecording()) {
				recorder.publish();
				recorder.dispose();
			}
		}
	}
	
	@Override
	public void redo() {
		CamelChangeRecorder2 recorder = PreDo();
		super.redo();
		PostDo(recorder);
	}

	@Override
	public void undo() {
		CamelChangeRecorder2 recorder = PreDo();
		super.undo();
		PostDo(recorder);
	}

	public void execute(Command command) {
		
		if (!canExecute()) {
			return;
		}
		
		CamelChangeRecorder2 recorder = PreDo();
		
		super.execute(command);
		
		PostDo(recorder);
	}

	private boolean canExecute() {
		return true;
	}

	private void setShouldRecord(boolean shouldRecord) {
		this.shouldRecord = shouldRecord;
	}

	private boolean getShouldRecord() {
		return shouldRecord;
	}
}
